import React from "react";
import Cookies from 'js-cookie';
import moment from 'moment';
import { connect } from "react-redux";
import { setSelectDate, setSelectDateRange, setProductInfo_0 } from '@/store/actions/order';
import { formatDate } from '@/utils';
// css
import styles from '@/styles/CommonOrder.module.scss';
// 组件
import _404 from '@/pages/404';
import Spin from '@/components/Spin';
import Breadcrumb from '@/components/Breadcrumb';
import Aside from './Aside';
import ProductInfo from './ProductInfo';
import EntryTime from "./EntryTime";
import DatePicker from "./DatePicker";
import OrderForm from "./OrderForm";
import OrderPay from "./OrderPay";
import Coupon from "./Coupon";
// api
import { productInstruction, priceCalendar } from '@/api/order';

class OrderMain extends React.Component {

    constructor(props) {
        super(props);
        this.clearCookies();
    }

    render() {
        // 页面报错
        const { error } = this.state;
        if (error === '404') {
            return <_404 />
        }
        // 传递数据
        const { target, routes } = this.props;
        const { goodsId, goodsName, goodsExtendId, goodsExtendName, predefinedInstructions, realName, buyLimit } = this.state;
        if (!goodsName) {
            return <Spin loading={true} />
        }
        return (
            <div className={styles['common-order-page']}>
                <div className="max-content">
                    {/* 面包屑 */}
                    <Breadcrumb params={routes} />
                    {/* 订单信息 */}
                    <div className={styles['product']}>
                        {/* 产品信息 */}
                        <ProductInfo data={{ goodsName, goodsExtendName, predefinedInstructions }} />
                        {/* 日期选择 */}
                        <DatePicker data={{ target, goodsId, goodsExtendName, buyLimit }} />
                        {/* 入园时间 */}
                        <EntryTime data={{ target }} />
                        {/* 下单信息填写 */}
                        <OrderForm data={{ target, goodsId, goodsExtendName, realName, buyLimit }} />
                        {/* 优惠券 */}
                        <Coupon data={{ target, goodsId, goodsExtendId, goodsExtendName }} />
                        {/* 确认下单 */}
                        <OrderPay data={{ target, realName, buyLimit }} />
                    </div>
                    {/* 右侧固定栏 */}
                    <Aside data={{ goodsName }} />
                </div>
            </div>
        )
    }

    state = {
        error: "",
        sr: "",                    // 是否展示入园时间，1 不展示 2 展示
        dn: "",                    // 目的地
        realName: 1,               // 1 无需实名  2 任一一名实名  3 所有实名 
        buyLimit: {                // 购买限制 type: 1 无限制， 2 有限制：less 最少购买数量，more 最多购买数量
            orderNumberLess: 0,
            orderNumberMore: 0,
            orderNumberType: 1,
            predefinedDay: -1      // -1不限制天数
        },
        goodsId: "",               // 商品id
        goodsName: "",             // 商品名称
        goodsExtendId: "",
        goodsExtendName: "",       // 子商品名称
        predefinedInstructions: "" // 购买须知
    }

    componentDidMount() {
        const { query: { order = [], sr, dn }, _setSelectDate } = this.props;
        const [goodsId, goodsExtendName] = order;
        // /instruction 接口
        productInstruction({ goodsId, goodsExtendName }).then(res => {
            const { code, data } = res;
            if (code === 0 && data) {

                const { goodsName, goodsExtendName, predefinedInstructions, refundRuleDTO, predefinedRuleAppDTO, requires } = data;
                const { realName, predefinedDay, orderNumberType, orderNumberLess, orderNumberMore } = predefinedRuleAppDTO;
                const { goodsExtendId } = refundRuleDTO;

                this.setState({
                    sr,
                    dn,
                    goodsId,
                    goodsName,
                    goodsExtendId,
                    goodsExtendName,
                    realName,
                    buyLimit: {
                        orderNumberType,
                        orderNumberLess,
                        orderNumberMore,
                        predefinedDay
                    },
                    predefinedInstructions
                });
                let amount = 1;
                // 根据realName=3时，默认数量为0
                if (realName === 3) {
                    amount = 0
                }

                Cookies.set('order_number', amount);
                Cookies.set('order_goodsExtendId', goodsExtendId);
                // 实名/时间类型/时间限制 等
                // 根据数据，判断产品预订日期，是否可选开始日期，存储在cookie中
                let init_predefinedLimitTime = "23:59",
                    startDate = formatDate(new Date());
                let { predefinedLimitType, predefinedLimitTime, predefinedLimitDay } = predefinedRuleAppDTO;
                if (predefinedLimitType == 2) {
                    let hour = new Date().getHours();
                    if (predefinedLimitTime !== init_predefinedLimitTime) {
                        if (hour >= predefinedLimitTime) {
                            predefinedLimitDay = predefinedLimitDay + 1;
                        }
                    }
                    startDate = moment(
                        new Date().getTime() + predefinedLimitDay * 24 * 60 * 60 * 1000
                    ).format("YYYY-MM-DD");
                    
                    _setSelectDate(startDate);
                    Cookies.set('order_select_date', startDate);
                    Cookies.set('extra_start_date', startDate);
                }
                // 本地添加年龄、性别等购买限制
                sessionStorage.setItem('requires', JSON.stringify(requires));
            } else {
                this.setState({
                    error: '404'
                })
            }
            // 价格日历
            sessionStorage.setItem('price_calendar', JSON.stringify([]));
            priceCalendar({
                goodsExtendId: Cookies.get('order_goodsExtendId')
            }).then(res => {
                const {code, data} = res;
                if(code === 0 && data){
                    sessionStorage.setItem('price_calendar', JSON.stringify(data.goodsPriceList));
                }
            })
        })
        document.body.className = "pop-datepicker";
    }
    componentWillUnmount() {
        const { _setSelectDate, _setSelectDateRange, _setProductInfo_0 } = this.props;
        const startDate = formatDate(new Date()),
              endDate = formatDate(new Date(), 1);
        this.clearCookies();
        _setProductInfo_0();
        _setSelectDate(startDate);
        _setSelectDateRange({startDate, endDate});
        document.body.className = "";
    }

    // 清除cookie数据
    clearCookies() {
        Cookies.remove('extra_start_date');
        Cookies.remove('order_select_date');
        Cookies.remove('order_select_customers');
        Cookies.remove('order_number');
        Cookies.remove('order_contact');
        Cookies.remove('order_phone');
        Cookies.remove('order_idcard');
        Cookies.remove('order_remark');
        Cookies.remove('order_goodsExtendId');
        Cookies.remove('order_spIds');
        Cookies.remove('order_hotel_startDate');
        Cookies.remove('order_hotel_endDate');
        Cookies.remove('order_coupon');
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        _setSelectDate: (v) => dispatch(setSelectDate(v)),
        _setSelectDateRange: (v) => dispatch(setSelectDateRange(v)),
        _setProductInfo_0: (v) => dispatch(setProductInfo_0(v)),
    }
};
export default connect(null, mapDispatchToProps)(OrderMain);